package com.primeton.poctag.api.customergroup;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.primeton.poctag.api.BaseController;
import com.primeton.poctag.core.model.ApiResponse;
import com.primeton.poctag.core.model.PageWrap;
import com.primeton.poctag.dao.customergroup.model.Customergroup;
import com.primeton.poctag.dto.QueryDto;
import com.primeton.poctag.service.customergroup.CustomergroupService;
import com.primeton.poctag.task.Data3CSparkQueue;
import com.primeton.poctag.task.SparkTask;
import com.primeton.poctag.task.SparkTaskFactory;
import com.primeton.poctag.util.ConditionUtil;
import com.primeton.poctag.util.RestApiUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客群接口
 * @author 李功林
 * @date 2021/08/20 10:14
 */
@Slf4j
@RestController
@RequestMapping("/customergroup")
public class CustomergroupController extends BaseController {

    @Autowired
    private CustomergroupService customergroupService;


    @Autowired
    ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    SparkTaskFactory sparkTaskFactory;

    /**
     * 客群导出XML
     */
    @Value("${datainsight.uaExportXmlFile}")
    String uaExportXmlFile;

    @Value("${explainIp}")
    private String explainIp;


    /**
     * 创建
     * @author 李功林
     * @date 2021/08/20 10:14
     */
    @PostMapping("/create")
    public ApiResponse create(@RequestBody Customergroup customergroup) {
        return ApiResponse.success(customergroupService.create(customergroup));
    }

    /**
     * 用户删除
     * @author 李功林
     * @date 2021/08/20 10:14
     */
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        customergroupService.deleteById(id);
        return ApiResponse.success(null);
    }

    /**
     * 修改用户
     * @author 李功林
     * @date 2021/08/20 10:14
     */
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody Customergroup customergroup) {
        customergroupService.updateById(customergroup);
        return ApiResponse.success(null);
    }

    /**
     * 分页查询
     * @author 李功林
     * @date 2021/08/20 10:14
     */
    @PostMapping("/page")
    public ApiResponse findPage (@RequestBody PageWrap<Customergroup> pageWrap) {
        return ApiResponse.success(customergroupService.findPage(pageWrap));
    }
    @PostMapping("/all")
    public ApiResponse findAll () {
        return ApiResponse.success(customergroupService.findAll());
    }

    /**
     * 通过ID查询
     * @author 李功林
     * @date 2021/08/20 10:14
     */
    @GetMapping("/{id}")
    public ApiResponse finById(@PathVariable Integer id) {
        return ApiResponse.success(customergroupService.findById(id));
    }


    /**
     * 导出
     * @param id
     * @return
     */
    @PostMapping("/ugExport/{id}")
    public ApiResponse ugExport(@PathVariable Integer id) throws IOException {
        // 通过客群参数，构造 SQL，然后调用： http://localhost:9200/_sql/_explain
        // 获取到 ES Query DSL，取其中的 query 子节点信息，放到 esQueryDsl 变量中
        String esQueryDsl = "";
        Customergroup customergroup = customergroupService.findById(id);
        String args = customergroup.getArgs();
        //args转化为QueryDto
        JSONArray jsonArray = JSONUtil.parseArray(args);
        List<QueryDto> queryDtos = jsonArray.toList(QueryDto.class);
        String sql = ConditionUtil.createSql(queryDtos,1);
        //获取查询结果
        Map<String, Object> result = RestApiUtils.post(explainIp, sql, false);
        JSONObject query = (JSONObject) result.get("query");
        esQueryDsl = query.toString();
        log.debug(esQueryDsl);
        // base64 序列化为 一行
        org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64(1, ":".getBytes());
        final String queryDsl = base64.encodeToString(esQueryDsl.getBytes(StandardCharsets.UTF_8));
        final Map taskInfo = new HashMap();
        taskInfo.put("queryDsl", "base64:" + queryDsl);
        taskInfo.put("taskType", "UG_EXPORT");
        // 其他参数
        try {
            // 构造 task
            final SparkTask sparkTask = sparkTaskFactory.newTask(String.valueOf(id), uaExportXmlFile, taskInfo);
            // 执行任务，等待返回
            final Map resultParam = Data3CSparkQueue.getInstance().execute(taskExecutor.getThreadPoolExecutor(), sparkTask);

            // 导出成功，更新数据库字段
            return ApiResponse.success("OK", resultParam);
        } catch (Exception e) {
            log.error("客群导出宽表异常。", e);
            return ApiResponse.failed(e.getMessage());
        }
    }
}
